package com.ruoyi.common.net.mqtt.multi;

import com.ruoyi.common.net.mqtt.IMessageHandler;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;

/**
 * @author xumh
 * @title: MqttClientCallback
 * @description: TODO
 * @date 2024/12/1815:01
 */
public class MqttClientCallback implements MqttCallbackExtended {
    private static Logger log = LoggerFactory.getLogger(MqttClientCallback.class);
    private String mqttClientId;
    private List<IMessageHandler> messageHandlers;

    public MqttClientCallback(String mqttClientId, List<IMessageHandler> messageHandlers) {
        this.mqttClientId = mqttClientId;
        this.messageHandlers = messageHandlers;
    }

    public void connectionLost(Throwable throwable) {
        log.info("断开了MQTT连接 ：{}", throwable.getMessage());
    }

    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("发布消息成功");
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        if (this.messageHandlers != null) {
            Iterator var3 = this.messageHandlers.iterator();

            while(var3.hasNext()) {
                IMessageHandler handler = (IMessageHandler)var3.next();
                handler.handle(this.mqttClientId, topic, new String(message.getPayload()), message);
            }

        }
    }

    public void connectComplete(boolean reconnect, String serverURI) {
        if (this.messageHandlers != null) {
            Iterator var3 = this.messageHandlers.iterator();

            IMessageHandler handler;
            while(var3.hasNext()) {
                handler = (IMessageHandler)var3.next();

                try {
                    handler.connected(reconnect, serverURI);
                } catch (Exception var6) {
                    var6.printStackTrace();
                }
            }

            if (reconnect) {
                try {
                    var3 = this.messageHandlers.iterator();

                    while(var3.hasNext()) {
                        handler = (IMessageHandler)var3.next();
                        handler.subscribe();
                    }
                } catch (Exception var7) {
                    var7.printStackTrace();
                }
            }

        }
    }
}

